package com.yst.web.utils;



import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class ThreadUtil {
    private static final Map<String, ThreadPoolExecutor> pools;
    static {
        pools= Collections.synchronizedMap(new HashMap<>());
    }

    public static final String DEFAULT="default";


    public static int DEFAULT_MAX_POOL_SIZE=4000;
    public static int DEFAULT_MAX_CORE_SIZE=3;

    public static String THREAD_PREFIX="TP-";

    public static ThreadPoolExecutor getThreadPool(String catalog){
        return pools.computeIfAbsent(catalog,(key)->
                new ThreadPoolBuilder().setCorePoolSize(DEFAULT_MAX_CORE_SIZE)
                        .setThreadFactory(r -> {
                            Thread result= new Thread(r);
                            result.setName(THREAD_PREFIX+catalog);
                            return result;
                        })
                .setKeepAliveTime(5, TimeUnit.MINUTES)
                .setMaxPoolSize(DEFAULT_MAX_POOL_SIZE)
                        .setHandler((r, executor) -> {
                            System.out.println("can't execute runnable "+r.toString());
                        })
                .build());
    }

    public static ThreadPoolExecutor getThreadPool(){
        return getThreadPool(DEFAULT);
    }

    public static void execute(Runnable runnable){
        getThreadPool().execute(runnable);
    }

    public static void execute(String catalog,Runnable runnable){
        getThreadPool(catalog).execute(runnable);
    }

}
